#include <iostream>
#include <memory>
#include <cstdio>
#include "UdpServer.hpp"
using namespace std;

string ExecuteCommand(string& command) {
    cout << "get a command: " << command << endl;
    FILE* fp = popen(command.c_str(), "r");
    if (fp == nullptr) {
        cout << "execute error reason unknown" << endl;
        exit(-1);
    }

    string response;
    char buffer[1024];
    while (true) {
        char *s = fgets(buffer, sizeof buffer, fp);
        if (!s) {
            break;
        } else {
            response += buffer;
        }
    }
    pclose(fp);
    return response.empty() ? "sucess" : response;
}

void Usage(const string& process) {
    cout << "Usage:\n\t" << process << " local_port\n" << endl;
}

int main(int argc, char* args[]) {
    if (argc != 2) {
        Usage(args[0]);
        return Usage_Erro;
    }
    uint16_t port = atoi(args[1]);
    UdpServer* ps = new UdpServer(port, ExecuteCommand);
    ps->Init();
    ps->Start();
    return 0;
}